const ExcelJS = require('exceljs');
const connection = require('../sql').rawPool;

async function exportStream(ctx, sql, params, options) {
  const { headerMap, fileName } = options;
  // 创建 Excel 工作簿
  const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
    useStyles: true,
    useSharedStrings: true
  });

  // 设置响应头
  ctx.set({
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}.xlsx"`
  });

  try {
    const worksheet = workbook.addWorksheet('Sheet 1');

    // 添加表头
    const headers = Object.values(headerMap);
    worksheet.addRow(headers);

    // 创建数据库查询流
    const queryStream = connection.query(sql, params).stream();

    // 流式处理数据
    queryStream
      .on('data', row => {
        const rowData = Object.keys(headerMap).map(key => row[key]);
        worksheet.addRow(rowData).commit();
      })
      .on('end', () => {
        worksheet.commit();
        // connection.release();
        pool.end();
        workbook.commit();
      });

    // 将 Excel 流管道到响应
    ctx.body = workbook.stream;
  } catch (error) {
    workbook.rollback();
    connection.release();
    pool.end();
    ctx.status = 500;
    ctx.body = { code: 500, message: '导出失败' };
    console.error('Export error:', error);
  }
}

module.exports = {
  exportStream
};
